package com.sgu6.sgu6_machine.ui.fragment.dialog;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.sgu6.middleware.manager.ThreadManager;
import com.sgu6.middleware.util.HexUtil;
import com.sgu6.middleware.util.HttpUtil;
import com.sgu6.serialport.manager.SerialPortManagerForCard;
import com.sgu6.sgu6_machine.App;
import com.sgu6.sgu6_machine.R;
import com.sgu6.sgu6_machine.adapter.MemberRechargeAdapter;
import com.sgu6.sgu6_machine.base.BaseF;
import com.sgu6.sgu6_machine.common.Constant;
import com.sgu6.sgu6_machine.container.MachineContainer;
import com.sgu6.sgu6_machine.dto.MemberCardInfoDto;
import com.sgu6.sgu6_machine.dto.SaleRulesDto;
import com.sgu6.sgu6_machine.event.ReadCardEvent;
import com.sgu6.sgu6_machine.event.RechargeEvent;
import com.sgu6.sgu6_machine.params.RechargeParam;
import com.sgu6.sgu6_machine.presenter.MachineP;
import com.sgu6.sgu6_machine.ui.dialog.RechargeDialogF;
import com.sgu6.sgu6_machine.util.QRCodeUtil;
import com.sgu6.sgu6_machine.util.ToastUtil;
import com.wang.avi.AVLoadingIndicatorView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MemberQueryF extends BaseF implements AdapterView.OnItemClickListener {

    @BindView(R.id.tvCardInfo)
    TextView tvCardInfo;
    @BindView(R.id.btnQuery)
    TextView btnQuery;

    @BindView(R.id.notice1)
    TextView notice1;
    @BindView(R.id.loading)
    AVLoadingIndicatorView loading;
    @BindView(R.id.content)
    RelativeLayout rlContent;
    @BindView(R.id.rl)
    RelativeLayout rl;
    @BindView(R.id.gvRules)
    GridView gvRules;
    @BindView(R.id.ivCode)
    ImageView ivCode;

    private String cardNo = "";
    private MachineP mp = new MachineP();
    private MemberRechargeAdapter adapter;
    private List<RechargeParam> rules = new ArrayList<>();
    private int ruleIndex = 0;
    private boolean isShow = false;
    private boolean hiddenUI = true;
    public static MemberQueryF newInstance(String params) {
        return new MemberQueryF();
    }


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        hiddenUI = hidden;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_dialog_query, container, false);
        unbinder = ButterKnife.bind(this, v);
        initUI();

        return v;
    }

    private void initUI() {
        adapter = new MemberRechargeAdapter(requireContext(), rules);
        gvRules.setAdapter(adapter);
        gvRules.setOnItemClickListener(this);
        mp.getSaleRules(1, MachineContainer.machineConfigDto.merchantId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        unbinder.unbind();
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    // TODO: 2020-09-25  如果查询失败，则隐藏查询中状态，提示未查询到，请重新输入
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMemberCardInfoEvent(MemberCardInfoDto memberCardInfoDto) {
        rlContent.setVisibility(View.VISIBLE);
        rl.setVisibility(View.INVISIBLE);
        String info = "卡号：" + memberCardInfoDto.getCardCode() + "\n\n米余额：" + memberCardInfoDto.getBalance()+ "\n\n水余额：" + memberCardInfoDto.getWaterBalance();
        tvCardInfo.setText(info);
        cardNo = memberCardInfoDto.getCardCode();
        updateQrCode();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onReadCardEvent(ReadCardEvent event) {
        if (event.cmd.length() == 40) {
            loading.setVisibility(View.GONE);
        }
    }


    @OnClick(R.id.btnQuery)
    public void onViewClicked() {
        EventBus.getDefault().post(new RechargeEvent());
    }


    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
        rules.get(ruleIndex).selected = false;
        rules.get(position).selected = true;
        ruleIndex = position;
        adapter.notifyDataSetChanged();
        updateQrCode();
    }

    public void updateQrCode() {
        if (cardNo.length() != 0) {
            String url = "{payDomain}/cart?orderNo={orderNo}&machineNo={machineNo}&payType={payType}&money={money}&merchantId={merchantId}&cardCode={cardNo}&rechargeType={rechargeType}&giftAmount={giftAmount}";
            ThreadManager.getThreadPollProxy().execute(new Runnable() {
                @Override
                public void run() {
                    if (isShow && hiddenUI){
                        ivCode.post(new Runnable() {
                            @Override
                            public void run() {
                                ivCode.setVisibility(View.GONE);
                                loading.setVisibility(View.VISIBLE);
                            }
                        });

                        String orderNo = HttpUtil.get((MachineContainer.machineConfigDto.isBeta ? MachineContainer.machineConfigDto.apiDomain : Constant.API_DOMAIN_DEV) + "/order/create_order_no");
                        if (orderNo != null) {
                            String newUrl = url.replace("{payDomain}", MachineContainer.machineConfigDto.payDomain).
                                    replace("{orderNo}", orderNo).
                                    replace("{machineNo}", MachineContainer.machineConfigDto.machineNo).
                                    replace("{payType}", "6").
                                    replace("{merchantId}", MachineContainer.machineConfigDto.merchantId).
                                    replace("{cardNo}", cardNo).
                                    replace("{money}", String.valueOf(rules.get(ruleIndex).rechargeValue)).
                                    replace("{rechargeType}", "1").
                                    replace("{giftAmount}", String.valueOf(rules.get(ruleIndex).giftValue));
                            Log.i(TAG, "run: " + newUrl);
                            ivCode.post(new Runnable() {
                                @Override
                                public void run() {
                                    ivCode.setImageBitmap(QRCodeUtil.createQRCodeBitmap(newUrl, 500, 500));
                                    ivCode.setVisibility(View.VISIBLE);
                                    loading.setVisibility(View.GONE);
                                }
                            });
                        }
                    }
                }
            });
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onSaleRuleEvent(SaleRulesDto saleRulesDto) {
        if (saleRulesDto != null && saleRulesDto.isEnable()) {
            isShow = true;
            String json_rules = saleRulesDto.getRule();
            JSONObject jo = null;
            try {
                jo = new JSONObject(json_rules);
                Iterator iterator = jo.keys();
                while (iterator.hasNext()) {
                    String key = (String) iterator.next();
                    String str_val = (String) jo.get(key);
                    int val = Integer.parseInt(str_val);
                    rules.add(new RechargeParam(Integer.parseInt(key), val, false));
                }
                rules.get(0).selected = true;
                adapter.notifyDataSetChanged();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void updateCardNo(String cardNo) {
        this.cardNo = cardNo;
        updateQrCode();
    }
}
